#include "ServClient.h"
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TBufferTransports.h>
#include <boost/thread/mutex.hpp> 


using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::protocol;

static boost::mutex g_insMutexCalc;
CServClient* CServClient::_instance = NULL;

CServClient* CServClient::instance() 
{	
	if (NULL == _instance)
	{
		boost::unique_lock<boost::mutex> guardMutex(g_insMutexCalc);
		if (NULL == _instance)
		{
			_instance = new CServClient;
		}
	}
	return _instance;
}


CServClient::CServClient()
{
	Init("localhost", 9090);
}

CServClient::CServClient(std::string serverAddr, int serverPort)
{
	Init(serverAddr, serverPort);
}


CServClient::~CServClient()
{
	m_transport->close();
}

void CServClient::Init(std::string serverAddr, int serverPort)
{
	m_socket = boost::shared_ptr<TSocket>(new TSocket(serverAddr, serverPort));
	m_transport = boost::shared_ptr<TTransport>(new TFramedTransport(m_socket));
	m_protocol = boost::shared_ptr<TProtocol>(new TBinaryProtocol(m_transport));  
  	m_servclient = boost::shared_ptr<ServClient>(new ServClient(m_protocol));

    m_socket->setRecvTimeout(2000);
    m_socket->setSendTimeout(2000);
    m_transport->open();
}

bool CServClient::IsOnline()
{
    return m_transport->isOpen();
}

void CServClient::Connect()
{
    m_transport->open();
}

bool CServClient::thriftMethod(std::string& _return, const std::string &openId, const std::string& method, const std::string& reqArgs)
{
    _return.clear();
    if(!m_transport->isOpen())
    {
        return false;
    }
    try
    {
        m_servclient->thriftMethod(openId, method, reqArgs);
    }
    catch(TTransportException &tx)
    {
        fprintf(stderr,"tx.getType(), tx.what()  %d  %s\n", tx.getType(), tx.what());
        m_transport->close();
        return false;
    }
    return true;
}

bool CServClient::thriftMethodSyn(std::string& _return, const std::string &openId, const std::string& method, const std::string& reqArgs)
{
    _return.clear();
    if(!m_transport->isOpen())
    {
        return false;
    }
    try
    {
        m_servclient->thriftMethodSyn(_return, openId, method, reqArgs);
    }
    catch(TTransportException &tx)
    {
        fprintf(stderr,"tx.getType(), tx.what()  %d  %s\n", tx.getType(), tx.what());
        m_transport->close();
        return false;
    }
    return true;
}


